const { loading } = require("../utils");
const t = require("../../config/dict");
const path = require("path");
const fs = require("fs");
const updateNative = require("../updateNative");

module.exports = (context) => {
  return loading(
    () => {
      return new Promise((resolve, reject) => {
        const projectType = context.metadata.projectType[0].toLowerCase();
        const projectDir =
          context.metadata.projectTechnologyStack +
          "/" +
          (context.metadata.projectTechnologyStack === "uniapp"
            ? /vue2/.test(projectType)
              ? "vue2/"
              : "vue3/"
            : context.metadata.projectTechnologyStack === "taro"
            ? /vue2/.test(projectType)
              ? "vue2/"
              : /react/.test(projectType)
              ? "react/"
              : "vue3/"
            : "") +
          (context.metadata.projectDevelopLang == "javascript"
            ? /vite/.test(projectType)
              ? "default-vite"
              : "default"
            : /vite/.test(projectType)
            ? "default-ts-vite"
            : "default-ts") +
          "/";
        const localScaffoldPath = path.resolve(
          __dirname,
          "../../baseTemplate/scaffold/modules/" + projectDir
        );
        const localTemplatePath = path.resolve(
          __dirname,
          "../../baseTemplate/template/modules/" + projectDir
        );
        const destPath = path.resolve(
          process.cwd(),
          context.metadata.projectDir
        );
        if (context.metadata.projectTechnologyStack !== "react-native") {
          if (fs.statSync(localScaffoldPath).isDirectory()) {
            fs.cp(localScaffoldPath, destPath, { recursive: true }, (err) => {
              if (err) {
                reject(err);
                return;
              }
              if (fs.statSync(localTemplatePath).isDirectory()) {
                fs.cp(
                  localTemplatePath,
                  destPath,
                  { recursive: true },
                  (err) => {
                    if (err) {
                      reject(err);
                      return;
                    }
                    resolve(context);
                  }
                );
              }
            });
          }
        } else {
          updateNative(context, {
            localScaffoldPath,
            localTemplatePath,
            destPath,
          })
            .then(() => resolve(context))
            .catch((err) => reject(err));
        }
      });
    },
    {
      start: [t(context.lang, "开始构建"), "..."].join(" "),
      succeed: [
        t(context.lang, "构建项目"),
        context.metadata.projectName,
        t(context.lang, "成功"),
        t(context.lang, "。"),
      ].join(" "),
      fail: [
        t(context.lang, "构建项目"),
        t(context.lang, "失败"),
        t(context.lang, "。"),
      ].join(" "),
    }
  );
};
